package com.mutouren.modules.datapush.local;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.mutouren.common.utils.HttpClientUtils;
import com.mutouren.common.utils.HttpResult;
import com.mutouren.modules.datapush.base.MethodType;
import com.mutouren.modules.datapush.base.PushMessage;
import com.mutouren.modules.datapush.base.PushStatus;
import com.mutouren.modules.datapush.server.AbstractServer;

public class LocalServer extends AbstractServer{

	public LocalServer(String serverAlias) {
		super(serverAlias, 50);
	}

	@Override
	protected void send(PushMessage message) {
		
		message.setRequestCount(message.getRequestCount() + 1);
		message.setLastUpdateTime(new Date());
				
		HttpClientUtils httpClient = new HttpClientUtils(message.getRealUrl(), message.getMethodType().name);
		try {
			if ((message.getMethodType() == MethodType.POST)&&(!StringUtils.isBlank(message.getRequestBody()))) {
				httpClient.setBody(message.getRequestBody(), message.getCharset().name, message.getContentType().name);
			}
			
			HttpResult httpResult = httpClient.execute();
			if(httpResult.isSuccess()) {
				String tempBody = httpResult.getContent(message.getCharset().name);
				message.setResponse(tempBody);
				if (checkSuccessFlag(message.getMethodAlias(), tempBody)) {
					message.setPushStatus(PushStatus.SUCCESS);
				} else {
					message.setPushStatus(PushStatus.FAIL);
				}				
			} else {
				message.setPushStatus(PushStatus.FAIL);
				message.setResponse(StringUtils.substring(httpResult.toString(message.getCharset().name), 0, 200));
			}						
		} catch (Throwable t) {
			message.setPushStatus(PushStatus.EXCEPTION);
			message.setResponse(StringUtils.substring(t.getMessage(), 0, 100));			
			errorLogger.error(this.getServerAlias() + " send pushMessage error", t);
		} finally {
			sendLogger.debug(String.format("serverAlias:%s, message:%s", this.getServerAlias(), JSON.toJSONString(message)));
		}
	}
	
}
